package com.hevs.samplewebapp.client.services;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.hevs.samplewebapp.client.Doctor;
import com.hevs.samplewebapp.client.bean.CompositeWRefresh;
import com.hevs.samplewebapp.client.bean.FakeSyncRestCall;
import com.hevs.samplewebapp.client.bean.JSONHelper;
import com.hevs.samplewebapp.client.bean.MedicalDataItem;
import com.hevs.samplewebapp.client.bean.MedicalDataJson;
import com.hevs.samplewebapp.client.bean.User;
import com.hevs.samplewebapp.client.bean.UserDataJson;
import com.hevs.samplewebapp.client.dialogbox.ServerResponseMessages;

/**
 * Implementation of the patient management service Interface
 * 
 * @author Thomas Rouvinez
 * @date 23.03.2012
 */
public class PatientManagementServiceImpl implements PatientManagementService
{
	/**
	 * List of patients
	 */
	private List<User> patientList=new ArrayList<User>();

	/**
	 * List of medical data
	 */
	private List<MedicalDataItem> medDatList=new ArrayList<MedicalDataItem>();

	@Override
	/**
	 * Get patients list
	 */
	public void getPatients()
	{
		String patientsUrl=Doctor.JSON_URL_PATIENTS;
		patientsUrl=URL.encode(patientsUrl);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.GET,patientsUrl);
		try
		{
			@SuppressWarnings("unused")
			Request request=builder.sendRequest(null,new RequestCallback()
			{
				@Override
				public void onError(Request request,Throwable exception)
				{
					Window.alert("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request request,Response response)
				{
					if(response.getStatusCode()==200)
						convertJSONToListPatient(JSONHelper.asArrayOfUserData(response.getText()));
					else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		}
		catch(Exception e)
		{
			Window.alert("Couldn't retrieve JSON");
			e.printStackTrace();
		}
	}

	@Override
	/**
	 * Get patients' medical data list
	 */
	public void getMedDats(String email, CompositeWRefresh comp)
	{
		String medDatsUrl=Doctor.JSON_URL_MEDICALRECORD;
		medDatsUrl+=email;
		medDatsUrl=URL.encode(medDatsUrl);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.GET,medDatsUrl);
		try
		{
			@SuppressWarnings("unused")
			Request request=builder.sendRequest(null,new FakeSyncRestCall(comp)
			{
				@Override
				public void onError(Request request,Throwable exception)
				{
					Window.alert("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request request,Response response)
				{
					if(response.getStatusCode()==200){
						// Get new list of medical data
						convertJSONToListMedDat(JSONHelper.asArrayOfMedicalData(response.getText()));
						refresh();
					}
					else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		}
		catch(Exception e)
		{
			Window.alert("Couldn't retrieve JSON");
			e.printStackTrace();
		}
	}

	@Override
	/**
	 * Update / Create a medical data
	 */
	public void update(JSONObject medDat, String email, CompositeWRefresh comp)
	{
		String medDatsUrl=Doctor.JSON_URL_MEDICALRECORD;
		medDatsUrl+=email;
		medDatsUrl=URL.encode(medDatsUrl);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.PUT,medDatsUrl);
		try
		{
			@SuppressWarnings("unused")
			Request request=builder.sendRequest(medDat.toString(),new FakeSyncRestCall(comp)
			{
				@Override
				public void onError(Request request,Throwable exception)
				{
					Window.alert("Couldn't retrieve JSON");
				}
				@Override
				public void onResponseReceived(Request request,Response response)
				{
					if(200==response.getStatusCode())
						refresh();
					else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		}
		catch(Exception e)
		{
			Window.alert("Couldn't retrieve JSON");
			e.printStackTrace();
		}
	}

	@Override
	/**
	 * Delete a medical data
	 */
	public void delete(JSONObject medDat, String email, CompositeWRefresh comp)
	{
		String medDatsUrl=Doctor.JSON_URL_MEDICALRECORD_DEL;
		medDatsUrl+=email;
		medDatsUrl=URL.encode(medDatsUrl);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.POST,medDatsUrl);
		try
		{
			@SuppressWarnings("unused")
			Request request=builder.sendRequest(medDat.toString(),new FakeSyncRestCall(comp)
			{
				@Override
				public void onError(Request request,Throwable exception)
				{
					Window.alert("Couldn't retrieve JSON");
				}

				@Override
				public void onResponseReceived(Request request,Response response)
				{
					if(200==response.getStatusCode())
						refresh();
					else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		}
		catch(Exception e)
		{
			Window.alert("Couldn't retrieve JSON");
			e.printStackTrace();
		}
	}

	/**
	 * Getter for the List of patients
	 * @return
	 * a List of patients in Java object Format
	 */
	public List<User> getPatientList()
	{
		return this.patientList;
	}

	/**
	 * Getter for the medical data list
	 * @return
	 * a List of medical data in Java object format
	 */
	public List<MedicalDataItem> getMedDatList()
	{
		return this.medDatList;
	}

	/**
	 * Method to convert the JSON patients list into Java Object
	 * @param array
	 * the JsonArray to convert from the server
	 */
	private void convertJSONToListPatient(JsArray<UserDataJson> array)
	{
		patientList.clear();
		for(int i=0;i<array.length();i++)
		{
			User patient=new User();
			UserDataJson temp=array.get(i);
			patient.setFirstName(temp.getFirstName());
			patient.setLastName(temp.getLastName());
			patient.setEmail(temp.getEmail());
			patientList.add(patient);
		}
	}

	/**
	 * Method to convert the JSON medical data list into Java Object
	 * @param array
	 * the JsonArray to convert from the server
	 */
	private void convertJSONToListMedDat(JsArray<MedicalDataJson> array)
	{
		medDatList.clear();
		for(int i=0;i<array.length();i++)
		{
			MedicalDataItem medDat=new MedicalDataItem();
			MedicalDataJson temp=array.get(i);
			medDat.setId(temp.getKey());
			medDat.setValue(temp.getValue());
			medDat.setDate(temp.getDate());
			medDat.setCategory(temp.getCategory());
			medDat.setType(temp.getType());
			medDatList.add(medDat);
		}
	}
}
